package edu.ncut.vod.jsf.examonline.selfmadevalidator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.sun.faces.util.MessageFactory;

import edu.ncut.vod.jsf.examonline.managedbeans.AddStudentBean;

public class IdentificationNumberValidator implements Validator {

    /**
     * validate field 'identificationNumber':its length must be 13 and must be number or English letter
     */
    public void validate(FacesContext context, UIComponent component, Object obj)
            throws ValidatorException {
        debug("method validate in class IdentificationNumberValidator is called");

        String label = ((HtmlInputText) component).getLabel();

        if("identificationNumber".equals(label)){
            String fieldValue = (String) obj;   // get the value of field which needs validating

            FacesContext facesContext = FacesContext.getCurrentInstance();

            // validate field 'humanId':its length must be 15 or 18
            boolean lengthMatch = false;
            if(15 == fieldValue.length() || 18 == fieldValue.length()){
				lengthMatch = true;
			}

            // validate field 'humanId':it must be number or English letter
            Pattern charPattern = Pattern.compile("^[A-Za-z0-9]+$");
            Matcher charMatcher = charPattern.matcher(fieldValue);
            boolean charMatch= charMatcher.matches();

            if (!lengthMatch && charMatch) {//validate field 'fieldValue':its length must be 15 or 18
                FacesMessage msg = MessageFactory.getMessage(facesContext,"identificationNumberLength_isNot15Or18","identificationNumberLength_isNot15Or18");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:identificationNumber", msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else if(lengthMatch && !charMatch){//validate field 'fieldValue':it must be number or English letter
                FacesMessage msg=MessageFactory.getMessage(facesContext,"identificationNumberLength_isNumberOrEnglishLetter","identificationNumberLength_isNumberOrEnglishLetter");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:identificationNumber",msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else if(!lengthMatch && !charMatch){//validate field 'fieldValue':its length must be 15 or 18 and must be number or English letter
                FacesMessage msg=MessageFactory.getMessage(facesContext,"identificationNumberLength_isNot15Or18AndMustBeNumberOrEnglishLetter","identificationNumberLength_isNot15Or18AndMustBeNumberOrEnglishLetter");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:identificationNumber",msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else{
				setErrorMessageInvisible();
			}
        }
    }

    /**
     * set error message tag of tag 'h:inputText' visible
     */
    public void setErrorMessageVisible(){
        debug("method setErrorMessageVisible in class IdentificationNumberValidator is called");

        FacesContext context =FacesContext.getCurrentInstance();
        Application application=context.getApplication();
        AddStudentBean addStudentBean=(AddStudentBean)application.evaluateExpressionGet(context,"#{addStudentBean}",AddStudentBean.class);

        addStudentBean.setIdentificationNumberNotice(true);
        addStudentBean.setIdentificationNumberMessage(true);
    }

    /**
	 * set error message tag of tag 'h:inputText' invisible
	 */
    public void setErrorMessageInvisible(){
		debug("method setErrorMessageInvisible in class IdentificationNumberValidator is called");

		FacesContext context =FacesContext.getCurrentInstance();
        Application application=context.getApplication();
        AddStudentBean addStudentBean=(AddStudentBean)application.evaluateExpressionGet(context,"#{addStudentBean}",AddStudentBean.class);

        addStudentBean.setIdentificationNumberNotice(false);
        addStudentBean.setIdentificationNumberMessage(false);
	}

    /**
     * print message on console
     * @param message
     */
    public void debug(String message){
        System.out.println(message);
    }
}
